# -*- coding:utf-8 -*-
import threading

from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from Apps.Interface.filters.interfaceTestFilter import InterfaceTestFilter
from Apps.Interface.models import InterfaceTest
from Apps.Interface.ser.interfaceTest import InterfaceTestSer
from Apps.common.interface.interface import RunInterfaceRequest
from Apps.common.response import SuccessResponse
import logging

logger = logging.getLogger("django")


class InterfaceTestView(ModelViewSet):
    queryset = InterfaceTest.objects.filter(is_deleted=False).all()
    serializer_class = InterfaceTestSer
    filter_class = InterfaceTestFilter

    # authentication_classes = []

    def create(self, request, *args, **kwargs):
        try:
            instance = InterfaceTest.objects.get(id=request.data["id"])
            # 如果已经有值的情况，调用修改方法
            if instance:
                logger.info(request.data["id"])
                serializer = self.get_serializer(instance, data=request.data, partial=True)
        except InterfaceTest.DoesNotExist:
            serializer = self.get_serializer(data=request.data)

        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return SuccessResponse("OK")

    def perform_create(self, serializer):
        serializer.save()


class RunInterfaceTestView(APIView):
    def post(self, request, *args, **kwargs):
        threading.Thread(target=RunInterfaceRequest().run_request,
                         args=(request.user, request.data,)).start()
        return SuccessResponse("ok")
